package com.qingcloud.adminbackend.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.f4b6a3.ulid.UlidCreator;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import com.qingcloud.adminbackend.base.AjaxResult;
import com.qingcloud.adminbackend.constant.WamingConstant;
import com.qingcloud.adminbackend.controller.open.param.OrgInfoParam;
import com.qingcloud.adminbackend.entity.config.SysCommonConfig;
import com.qingcloud.adminbackend.entity.sysfunction.SysOrgFunction;
import com.qingcloud.adminbackend.entity.sysfunction.SysOrgModule;
import com.qingcloud.adminbackend.entity.sysorder.SysOrder;
import com.qingcloud.adminbackend.entity.sysorg.*;
import com.qingcloud.adminbackend.entity.user.SysUser;
import com.qingcloud.adminbackend.entity.user.SysUserVo;
import com.qingcloud.adminbackend.entity.user.UserRoleBo;
import com.qingcloud.adminbackend.entity.userrole.SysUserRole;
import com.qingcloud.adminbackend.entity.userrole.UserRoleVO;
import com.qingcloud.adminbackend.enums.UserRoleEnum;
import com.qingcloud.adminbackend.mapper.*;
import com.qingcloud.adminbackend.service.ISysOrgService;
import com.qingcloud.adminbackend.service.ISysUserService;
import com.qingcloud.adminbackend.utils.CommonUtil;
import com.qingcloud.adminbackend.utils.OrgUtil;
import com.qingcloud.adminbackend.utils.PinYinUtil;
import com.qingcloud.adminbackend.utils.StringUtil;
import com.qingcloud.base.constant.SecurityConstants;
import com.qingcloud.base.passwordencode.Md5PasswordEncoder;
import com.qingcloud.base.remote.pojo.LoginUserDTO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 客户表 服务实现类
 * </p>
 *
 * @author liyuhong
 * @since 2018-11-15
 */
@Service
public class SysOrgServiceImpl extends ServiceImpl<SysOrgMapper, SysOrg> implements ISysOrgService {

    @Resource
    private SysFunctionMapper sysFunctionMapper;

    @Resource
    private Md5PasswordEncoder md5PasswordEncoder;

    /*@Resource
    private SysUserGroupRoleMapper sysUserGroupRoleMapper;*/
    @Resource
    private SysStationGroupMapper sysStationGroupMapper;
    @Resource
    private SysUsergroupMapper sysUsergroupMapper;
    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private SysOrderMapper sysOrderMapper;
    @Resource
    private SysUserOrgMapper sysUserOrgMapper;
    @Resource
    private SysUserOrgMgrMapper sysUserOrgMgrMapper;
    @Resource
    private SysCommonConfigMapper commonConfigMapper;
    @Resource
    private SysUserRoleMapper sysUserRoleMapper;
    @Resource
    private SysUserFunctionMapper sysUserFunctionMapper;
    @Resource
    private SysUserOrderStationmgrMapper sysUserOrderStationmgrMapper;
    @Resource
    private SysOrgMapper sysOrgMapper;

    @Resource
    private SysUserTaskOrgMapper userTaskOrgMapper;

    @Resource
    private ISysUserService sysUserService;

    @Resource
    private SysRoleMapper sysRoleMapper;

    /**
     * 客户列表
     *
     * @param sysOrgDTO
     * @param isAdmin
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public IPage<SysOrgBO> findSysOrgList(SysOrgDTO sysOrgDTO, boolean isAdmin) {
        Page<SysOrgBO> page = new Page<>(sysOrgDTO.getCurrentPage(), sysOrgDTO.getPerPage());
        return findWMuserOrg(sysOrgDTO, isAdmin, page);
    }

    /**
     * 普通用户查询客户列表
     *
     * @param sysOrgDTO
     * @param page
     * @return
     */
    public IPage<SysOrgBO> finduserOrg(SysOrgDTO sysOrgDTO, Page<SysOrgBO> page) {
        List<SysOrgBO> bos;
        IPage<SysOrgBO> sysOrgIds = this.baseMapper.findSysOrgByUserId(page, sysOrgDTO);
        List<SysOrgBO> records = sysOrgIds.getRecords();
        if (!StringUtils.isEmpty(records) && records.size() > 0) {
            SysOrgBO sysOrgBO = records.get(0);
            if (sysOrgBO.getCategory() == 1) {
                bos = this.baseMapper.findChildUserOrgList(sysOrgBO.getId(), sysOrgDTO);
                if (records.size() == 0 && bos.size() > 0) {
                    sysOrgBO = this.baseMapper.findUserOrg(sysOrgBO.getId());
                }
                sysOrgBO.setChildSysOrgs(bos);
            }
        }
        return sysOrgIds.setRecords(records);
    }

    /**
     * 蛙鸣客服查询客户列表
     *
     * @param sysOrgDTO
     * @param isAdmin
     * @param page
     * @return
     */
    public IPage<SysOrgBO> findWMuserOrg(SysOrgDTO sysOrgDTO, boolean isAdmin, Page<SysOrgBO> page) {
        Set<String> orgIds = new HashSet<>();
        Set<String> sysOrgIds;
        Set<SysOrgBO> bos;
        if (isAdmin) {
            //查询属于该用户的一级客户
            sysOrgIds = this.baseMapper.findSysOrgIds(sysOrgDTO);
        } else {
            //查询属于该用户的一级客户
            sysOrgIds = this.baseMapper.findSysOrgMgrIds(sysOrgDTO);
        }
        sysOrgIds.stream().forEach(it -> {
            orgIds.add(it);
        });
        //当有搜索条件时查询分支机构下是否由符合条件的数据
        Set<String> childSysOrgIds = new HashSet<>();
        Map<String, List<SysOrgBO>> map = new HashMap<>();
        //判断是否有搜索条件
        if (!StringUtils.isEmpty(sysOrgDTO.getName())) {
            bos = this.baseMapper.findChildSysOrgList(null, sysOrgDTO);
            bos.stream().forEach(it -> {
                orgIds.add(it.getParentId());
                if (!sysOrgIds.contains(it.getParentId())) {
                    if (!childSysOrgIds.contains(it.getParentId())) {
                        List<SysOrgBO> list = new ArrayList<>();
                        list.add(it);
                        map.put(it.getParentId(), list);
                    } else {
                        map.get(it.getParentId()).add(it);
                    }
                    childSysOrgIds.add(it.getParentId());
                }
            });
        }
        if (orgIds.size() == 0) {
            return null;
        }
        IPage<SysOrgBO> orgList = this.baseMapper.findSysOrgList(page, orgIds, sysOrgDTO.getUserId(), isAdmin);
        List<SysOrgBO> records = orgList.getRecords();
        Set<String> ids = new HashSet<>();
        records.stream().forEach(it -> {
            if (childSysOrgIds.contains(it.getId())) {
                it.setChildSysOrgs(map.get(it.getId()));
            } else {
                ids.add(it.getId());
            }
        });
        sysOrgDTO.setName(null);
        if (ids.size() > 0) {
            Set<SysOrgBO> childSysOrgs = this.baseMapper.findChildSysOrgList(ids, sysOrgDTO);
            Set<String> childOrgIds = new HashSet<>();
            Map<String, List<SysOrgBO>> hashmap = new HashMap<>();
            childSysOrgs.stream().forEach(it -> {
                if (!childOrgIds.contains(it.getParentId())) {
                    List<SysOrgBO> list = new ArrayList<>();
                    list.add(it);
                    hashmap.put(it.getParentId(), list);
                } else {
                    hashmap.get(it.getParentId()).add(it);
                }
                childOrgIds.add(it.getParentId());
            });

            //查询所有业务种类
//            List<SysBusinessTypeDTO> data = sysOrderMapper.getBusinessTypeByUserId(null, true, true);
//            Map<String, SysBusinessTypeDTO> businessTypeMap = data.stream().collect(Collectors.toMap(SysBusinessTypeDTO::getValue, o -> o));

            records.stream().forEach(it -> {
                if (childOrgIds.contains(it.getId())) {
                    it.setChildSysOrgs(hashmap.get(it.getId()));
                }
//                List<String> businessTypes = Arrays.asList(it.getBusinessType().split(","));
//                List<String> newTypes = new ArrayList<>();
//                for (String businessType : businessTypes) {
//                    SysBusinessTypeDTO typeDTO = businessTypeMap.get(businessType);
//                    newTypes.add(typeDTO.getName());
//                }
//                String typeStr = String.join(",", newTypes);
//                it.setBusinessTypeDesc(typeStr);
            });
        }
        return orgList.setRecords(records);
    }

    public Set<String> parentFunctionIds(Set<String> set, Set<String> parentIds) {
        set = sysFunctionMapper.findParentIdByIds(set);
        if (!StringUtils.isEmpty(set) && set.size() > 0) {
            set.stream().forEach(it -> {
                parentIds.add(it);
            });
            parentFunctionIds(set, parentIds);
        }
        return parentIds;
    }

    /**
     * 整理的绑定功能
     *
     * @return
     */
    public Set<String> addfunctionIds(SysOrg sysOrg) {
        //整理的绑定功能
        Set<String> set = new HashSet<>();
        //已绑定的功能
        if (!StringUtils.isEmpty(sysOrg.getFunctionIds()) && sysOrg.getFunctionIds().size() > 0) {
            Set<String> functions = sysOrg.getFunctionIds();
            for (String functionId : functions) {
                set.add(functionId);
            }
        }
        //已绑定模块的相关功能
        if (!StringUtils.isEmpty(sysOrg.getModuleIds()) && sysOrg.getModuleIds().size() > 0) {
            Set<String> mfunctionIds = sysFunctionMapper.getFunctionByModuleId(sysOrg.getModuleIds());
            for (String functionId : mfunctionIds) {
                set.add(functionId);
            }
        }
        /*if (!StringUtils.isEmpty(set) && set.size() > 0) {
            set = parentFunctionIds(set, set);
        }*/
        /*if (!StringUtils.isEmpty(sysOrg.getOrderIds()) && sysOrg.getOrderIds().size() > 0 && set.size() == 0) {
            set = sysFunctionMapper.getOrderFunctionIdsByOrderIds(sysOrg.getOrderIds());
        }*/
        return set;
    }

    /**
     * 整理绑定的模块
     *
     * @param sysOrg
     * @return
     */
    public Set<String> addModuleIds(SysOrg sysOrg) {
        //整理的绑定功能
        Set<String> set = new HashSet<>();
        //已绑定模块
        if (!StringUtils.isEmpty(sysOrg.getModuleIds()) && sysOrg.getModuleIds().size() > 0) {
            for (String moduleId : sysOrg.getModuleIds()) {
                set.add(moduleId);
            }
        }
        //订单关联的模块
        /*if (!StringUtils.isEmpty(sysOrg.getOrderIds()) && sysOrg.getOrderIds().size() > 0 && set.size() == 0) {
            set = sysFunctionMapper.getOrderModuleIdsByOrderIds(sysOrg.getOrderIds());
        }*/
        return set;
    }

    public String defaultUserName() {
        //随机登录名
        String s = StringUtil.generateString(10);
        //检测是数据库中是否存在
        Boolean aBoolean = userNameExist(s);
        if (aBoolean) {
            return defaultUserName();
        } else {
            return s;
        }
    }

    public Boolean userNameExist(String userName) {
        QueryWrapper<SysUser> userParam = new QueryWrapper<>();
        userParam.eq("user_name", userName);
        userParam.eq("delete_flag", 0);
        Long count = sysUserMapper.selectCount(userParam);
        if (count <= 0) {
            return false;
        }
        return true;
    }

    /**
     * 添加企业管理员
     */
    public void addCompanyAdmin(SysOrg sysOrg, boolean isAdmin) {
        SysUser user = sysOrg.getUser();
        if (!StringUtils.isEmpty(user)) {
            //添加管理员
            user.setId(UUID.randomUUID().toString().replace("-", ""));
            if (!StringUtils.isEmpty(user.getUserName())) {
                user.setIsDefault(0);
            } else {
                user.setUserName(defaultUserName());
                user.setIsDefault(1);
            }
            QueryWrapper<SysCommonConfig> query = new QueryWrapper<>();
            query.eq("`key`", "user_default_pwd");
            SysCommonConfig sysCommonConfig = commonConfigMapper.selectOne(query);
            String defaultPwd = StringUtils.isEmpty(sysCommonConfig.getValue()) ? WamingConstant.DEFAULT_PWD : sysCommonConfig.getValue();
            user.setFullNamePinyin(PinYinUtil.cn2Spell(user.getFullName()));
            user.setUserPassword(md5PasswordEncoder.encodePassword(defaultPwd, user.getId()));
            user.setStatus("0");
            user.setCreateBy(sysOrg.getCreateBy());
            user.setCreateDt(new Date());
            int userType;
            if ("1".equals(sysOrg.getBusinessType())) {
                userType = 3;
            } else {
                userType = 1;
            }
            user.setUserType(userType);
            user.setDeleteFlag("0");
            user.setOrgAdmin(1);
            sysUserMapper.insert(user);
            //添加管理员所属客户关系
            SysUserOrg sysUserOrg = new SysUserOrg();
            sysUserOrg.setUserId(user.getId());
            sysUserOrg.setOrgId(sysOrg.getId());
            sysUserOrg.setCreateBy(sysOrg.getCreateBy());
            sysUserOrg.setCreateDt(new Date());
            sysUserOrgMapper.insert(sysUserOrg);
            //添加管理员的管理权限
            SysUserOrgMgr sysUserOrgMgr = new SysUserOrgMgr();
            sysUserOrgMgr.setOrgId(sysOrg.getId());
            sysUserOrgMgr.setUserId(user.getId());
            sysUserOrgMgr.setManage(1);
            sysUserOrgMgr.setRead(1);
            sysUserOrgMgr.setRoleId(UserRoleEnum.COMPANY_MANAGER_ID.code);
            sysUserOrgMgr.setCreateBy(sysOrg.getCreateBy());
            sysUserOrgMgr.setCreateDt(new Date());
            sysUserOrgMgrMapper.insertSysUserOrgMgr(sysUserOrgMgr);
            //添加创建客户的管理权限
            if (!isAdmin) {
                List<UserRoleVO> roles = sysUserRoleMapper.findRoleByUserId(sysOrg.getCreateBy());
                roles.stream().forEach(it -> {
                    SysUserOrgMgr userOrgMgr = new SysUserOrgMgr();
                    userOrgMgr.setOrgId(sysOrg.getId());
                    userOrgMgr.setUserId(sysOrg.getCreateBy());
                    userOrgMgr.setManage(1);
                    userOrgMgr.setRead(1);
                    userOrgMgr.setRoleId(it.getId());
                    userOrgMgr.setCreateBy(sysOrg.getCreateBy());
                    userOrgMgr.setCreateDt(new Date());
                    sysUserOrgMgrMapper.insertSysUserOrgMgr(userOrgMgr);
                });
            }
            //初始化用户身份
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setRoleId(UserRoleEnum.COMPANY_MANAGER_ID.code);
            sysUserRole.setUserId(user.getId());
            sysUserRole.setCreateBy(sysOrg.getCreateBy());
            sysUserRole.setCreateDt(new Date());
            sysUserRoleMapper.insert(sysUserRole);
        }
    }

    /**
     * 添加客户
     *
     * @param sysOrg
     */
    public void addSysOrg(SysOrg sysOrg, boolean isAdmin) {
        //添加客户
        //判断是分支机构还是一级客户
        if (sysOrg.getCategory() == 2) {
            SysOrg sysOrgById = this.baseMapper.findSysOrgById(sysOrg.getParentId());
            sysOrg.setBusinessType(sysOrgById.getBusinessType());
            sysOrg.setType(sysOrgById.getType());
        }
        String orgId = UUID.randomUUID().toString().replace("-", "");
        sysOrg.setId(orgId);
        sysOrg.setDeleteFlag(0);
        this.baseMapper.insertSysOrg(sysOrg);

        if (sysOrg.getBusinessLogoList() != null && sysOrg.getBusinessLogoList().size() > 0) {
            for (SysOrgLogoDTO logoDTO : sysOrg.getBusinessLogoList()) {
                logoDTO.setOrgId(orgId);
            }
            this.baseMapper.insertOrgLogo(sysOrg.getBusinessLogoList());
            //更新组织业务种类
            String business = sysOrgMapper.findOrgAllBusiness(orgId);
            sysOrgMapper.updateOrgBusiness(business, orgId);
        }

        //添加管理员
        addCompanyAdmin(sysOrg, isAdmin);
    }

    /**
     * 修改客户
     *
     * @param sysOrg
     */
    public AjaxResult updateSysOrg(SysOrg sysOrg) {
        //订单详情
        SysOrg sysOrgBo = this.baseMapper.findSysOrgById(sysOrg.getId());

        //判断业务种类是否修改
        if (!sysOrgBo.getBusinessType().equals(sysOrg.getBusinessType())) {
            //获取删除的业务种类
            //原业务种类
            String[] originBusinessTypes = sysOrgBo.getBusinessType().split(",");
            List newBusinessTypes = Arrays.asList(sysOrg.getBusinessType().split(","));
            //待删除的业务种类
            List<String> delTyps = new ArrayList();
            for (String oriType : originBusinessTypes) {
                if (!newBusinessTypes.contains(oriType)) {
                    delTyps.add(oriType);
                }
            }
            delRelationBusinessType(sysOrg.getId(), delTyps);
            if (sysOrg.getCategory() == 1) {//客户
                //修改下级分支机构的类型
                this.baseMapper.updateChildSysOrg(sysOrg);
                //清理分支机构相关的业务关系
                Set<SysOrg> sysOrgs = this.baseMapper.findChildSysOrgListV2(Arrays.asList(sysOrg.getId()));
                for (SysOrg org : sysOrgs) {
                    delRelationBusinessType(org.getId(), delTyps);
                }
            }
        }
        //修改客户
        sysOrg.setModifyBy(sysOrg.getCreateBy());
        this.baseMapper.updateSysOrg(sysOrg);
        //删除logo信息
        sysOrgMapper.deleteOrgBusiness(sysOrg.getId());
        //插入logo信息
        for (SysOrgLogoDTO sysOrgLogoDTO : sysOrg.getBusinessLogoList()) {
            sysOrgLogoDTO.setOrgId(sysOrg.getId());
        }
        sysOrgMapper.insertOrgLogo(sysOrg.getBusinessLogoList());
        //清除原有关系
        sysFunctionMapper.deleteSysOrgFunction(Arrays.asList(sysOrg.getId()));
//        sysFunctionMapper.deleteModule(Arrays.asList(sysOrg.getId()));
        return null;
    }

    /**
     * 删除客户业务种类时清理相关关系
     *
     * @param orgId   客户ID
     * @param delTyps
     */
    private void delRelationBusinessType(String orgId, List<String> delTyps) {
        //已关联的项目
        List<Map> os = sysOrderMapper.findOrderByOrgId(orgId);
        if (os.size() > 0 && delTyps.size() > 0) {
            for (String businessType : delTyps) {
                for (Map map : os) {//待删除的业务种类已经关联了订单 ，删除改关联关系
                    if (businessType.equals(String.valueOf(map.get("business_type")))) {
                        //解除项目与该客户的关联关系
                        sysOrderMapper.updateBusinessTypeByOrgIds(Arrays.asList(orgId));
                    }
                }
            }
        }
        //客户下是否存在其他用户
        List<SysUserOrgDTO> ucount = this.baseMapper.findSysUserOrgByorgIds(Arrays.asList(orgId));
        //客户管理员，不做处理，适配老版本，目前未启用该功能
        List<SysUserOrgDTO> userfalg = new ArrayList<>();
        ucount.stream().forEach(it -> {
            if (it.getOrgAdmin() == 1) {
                userfalg.add(it);
            }
        });
        ucount = CommonUtil.removeAll(ucount, userfalg);
        if (ucount.size() > 0 && delTyps.size() > 0) {
            for (SysUserOrgDTO userOrgDTO : ucount) {
                List<Integer> roleIds = new ArrayList<>();
                //判断是否修改了身份
                List<UserRoleVO> userRole = sysUserRoleMapper.findRoleByUserId(userOrgDTO.getUserId());
                for (UserRoleVO roleVO : userRole) {
                    for (String businessType : delTyps) {
                        if (businessType.equals(roleVO.getBusinessType())) {
                            roleIds.add(roleVO.getId());
                        }
                    }
                }
                if (roleIds.size() > 0) {
                    //删除角色关系
                    QueryWrapper<SysUserRole> userrole = new QueryWrapper<>();
                    userrole.eq("user_id", userOrgDTO.getUserId());
                    userrole.in("role_id", roleIds);
                    sysUserRoleMapper.delete(userrole);
                }
            }
        }
    }

    /**
     * 绑定功能
     *
     * @param set
     * @param sysOrg
     */
    public void addSysOrgFunction(Set<String> set, SysOrg sysOrg) {
        //绑定功能
        List<SysOrgFunction> list = new ArrayList<>();
        if (!StringUtils.isEmpty(set) && set.size() > 0) {
            for (String functionId : set) {
                if (!StringUtils.isEmpty(functionId)) {
                    SysOrgFunction sysOrgFunction = new SysOrgFunction();
                    sysOrgFunction.setOrgId(sysOrg.getId());
                    sysOrgFunction.setFunctionId(functionId);
                    sysOrgFunction.setCreateBy(sysOrg.getCreateBy());
                    list.add(sysOrgFunction);
                }
            }
            this.baseMapper.insertSysOrgFunction(list);
        }
    }

    /**
     * 绑定模块
     *
     * @param modules
     * @param sysOrg
     */
    public void addSysOrgModule(Set<String> modules, SysOrg sysOrg) {
        //绑定模块
        List<SysOrgModule> moduleDTOS = new ArrayList<>();
        if (!StringUtils.isEmpty(modules) && modules.size() > 0) {
            if (!StringUtils.isEmpty(modules) && modules.size() > 0) {
                for (String moduleId : modules) {
                    if (!StringUtils.isEmpty(moduleId)) {
                        SysOrgModule moduleDTO = new SysOrgModule();
                        moduleDTO.setOrgId(sysOrg.getId());
                        moduleDTO.setModuleId(moduleId);
                        moduleDTO.setCreateBy(sysOrg.getCreateBy());
                        moduleDTOS.add(moduleDTO);
                    }
                }
//                if (CollUtil.isNotEmpty(moduleDTOS)) {
//                    sysFunctionMapper.insertSysOrgModule(moduleDTOS);
//                }
            }
        }
    }

    /**
     * 添加修改客户
     *
     * @param sysOrg
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult setSysOrg(SysOrg sysOrg, boolean isAdmin) {
        //整理的绑定功能
        Set<String> set = addfunctionIds(sysOrg);
        //整理绑定的模块
        Set<String> modules = addModuleIds(sysOrg);
        //添加-修改客户
        if (StringUtils.isEmpty(sysOrg.getId())) {
            //添加客户
            addSysOrg(sysOrg, isAdmin);
        } else {
            //修改客户
            AjaxResult ajaxResult = updateSysOrg(sysOrg);
            if (!StringUtils.isEmpty(ajaxResult)) {
                return ajaxResult;
            }
        }
        //绑定功能
        addSysOrgFunction(set, sysOrg);
        //绑定模块
//        addSysOrgModule(modules, sysOrg);
        return new AjaxResult(WamingConstant.SUCCESS, null, "操作成功");
    }

    /**
     * 删除客户
     *
     * @param ids
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult deleteSysOrg(List<String> ids) {
        //已关联的订单
        long orderNum = sysOrderMapper.findOrderByOrgIds(ids);
        if (orderNum > 0) {
            return new AjaxResult(WamingConstant.FAILURE, "已关联订单客户不能删除");
        }
        //验证客户下是否存在用户
        List<SysUserOrgDTO> countUser = this.baseMapper.findSysUserOrgByorgIds(ids);
        List<SysUserOrgDTO> userfalg = new ArrayList<>();
        countUser.stream().forEach(it -> {
            if (it.getOrgAdmin() == 1) {
                userfalg.add(it);
            }
        });
        countUser = CommonUtil.removeAll(countUser, userfalg);
        if (countUser.size() > 0) {
            return new AjaxResult(WamingConstant.FAILURE, "客户下存在普通用户不可删除");
        }
        //验证客户下是否存在分支机构（如果包含分支机构，则看所包含的分支机构是否被选择）
        List<String> countOrg = this.baseMapper.findSysOrgByorgIds(ids);
        if (!StringUtils.isEmpty(countOrg) && countOrg.size() > 0) {
            countOrg.removeAll(ids);
            if (countOrg.size() > 0) {
                return new AjaxResult(WamingConstant.FAILURE, "客户下存在分支机构不可删除");
            }
        }
        //删除客户
        this.baseMapper.deleteSysOrg(ids);
        //删除客户选择功能
        sysFunctionMapper.deleteSysOrgFunction(ids);
        //删除客户选择模块
//        sysFunctionMapper.deleteModule(ids);
        List<String> stationGroupIds = sysStationGroupMapper.findStationGroupByOrgIds(ids);
        if (stationGroupIds.size() > 0) {
            //删除用户关联的设备组
            sysStationGroupMapper.deleteUserStationGroup(stationGroupIds);
            //删除设备组关联的设备
            sysStationGroupMapper.deleteStationGroupEquipment(stationGroupIds);
        }
        //删除设备组
        sysStationGroupMapper.deleteStationGroup(ids);
        //删除客户可用设备组
        sysStationGroupMapper.deleteOrgStationGroup(ids);
        //删除客户下的所属用户表
        this.baseMapper.deleteUserOrg(ids);
        if (userfalg.size() > 0) {
            //删除客户下的企业管理员
            sysUserMapper.deleteById(userfalg.get(0).getUserId());
            //删除客户下的企业管理员的身份
            Map<String, Object> columnMap = Maps.newHashMap();
            columnMap.put("user_id", userfalg.get(0).getUserId());
            sysUserRoleMapper.deleteByMap(columnMap);
            //删除客户下的企业管理员的功能
            Map<String, Object> map = Maps.newHashMap();
            map.put("user_id", userfalg.get(0).getUserId());
            sysUserFunctionMapper.deleteByMap(map);
        }
        //删除客户下的有管理权限的用户
        this.baseMapper.deleteUserOrgMgr(ids);
        //查询该看客户下的用户组Id
        List<String> userGroup = sysUsergroupMapper.findUserGroup(ids);
        if (userGroup.size() > 0) {
            //根据客户Id删除用户组
            sysUsergroupMapper.deleteUserGroup(ids);
            //删除用户组与用户的关系
            sysUsergroupMapper.deleteUserGroupUser(userGroup);
            //删除用户组与设备组的关系
            sysUsergroupMapper.deleteUserGroupStationGroup(userGroup);
        }
        //解除订单和客户关系
        sysOrderMapper.updateSysOrderByOrgIds(ids);
        sysOrderMapper.updateBusinessTypeByOrgIds(ids);
        return new AjaxResult(WamingConstant.SUCCESS, null, "删除成功");
    }

    /**
     * 客户详情
     *
     * @param id
     * @return
     */
    @Override
    public SysOrg findSysOrgById(String id) {
        final SysOrg org = this.baseMapper.findSysOrgById(id);
        if (org != null) {
            org.setFunctionIds(sysFunctionMapper.getFunctionByOrgId(id));
//            Set<ModuleDTO> moduleByOrgIds = sysFunctionMapper.getModuleByOrgId(id);
//            List<String> set = new ArrayList<>();
//            for (ModuleDTO moduleDTO : moduleByOrgIds) {
//                set.add(moduleDTO.getId());
//            }
//            org.setModuleDTOs(moduleByOrgIds);
//            org.setModuleIds(set);
            List<Map> orders;
            if (org.getCategory() == 1) {
                orders = sysOrderMapper.findOrderByOrgId(id);
            } else {
                orders = sysOrderMapper.findOrderByOrgId(org.getParentId());
            }
            orders.stream().forEach(it -> {
                org.getOrderIds().add(String.valueOf(it.get("id")));
            });
            if (!StringUtils.isEmpty(org.getOrderIds()) && org.getOrderIds().size() > 0) {
                org.setOrderFunctionIds(sysFunctionMapper.getOrderFunctionIdsByOrderIds(org.getOrderIds()));
            }
        }
        return org;
    }

    /**
     * 客户内的订单
     *
     * @param sysOrgOrderDTO
     * @return
     */
    @Override
    public IPage<SysOrder> findOrgOrderByOrgId(SysOrgOrderDTO sysOrgOrderDTO) {
        Page<SysOrgOrderDTO> page = new Page<>(sysOrgOrderDTO.getCurrentPage(), sysOrgOrderDTO.getPerPage());
        return sysOrderMapper.findOrgOrderByOrgId(page, sysOrgOrderDTO);
    }

    /**
     * 当前登录用户的客户管理权限范围内的有写权限的组织
     *
     * @param orgId
     * @param userId
     * @param isAdmin
     * @return
     */
    @Override
    public List<SysOrg> findOrgByUserOrg(String orgId, String userId, Boolean isAdmin) {
        //获取登录用户的可管理客户
        List<SysOrg> allManageOrgByUser = getUserMgrOrg(isAdmin, userId, null);
        //
        List<String> orgIds = new ArrayList<>();
        allManageOrgByUser.forEach(e -> orgIds.add(e.getId()));

        List<SysOrg> resultTemp = new ArrayList<>();
        //被授权用户所属客户
        QueryWrapper<SysOrg> query = new QueryWrapper<>();
        query.eq("id", orgId);
        query.eq("delete_flag", "0");
        SysOrg sysOrgById = baseMapper.selectOne(query);
        List<SysOrg> tempSysOrg = new ArrayList<>();
        String parentId;
        SysOrg parent;
        if (sysOrgById.getCategory() == 1) {
            tempSysOrg.add(sysOrgById);
            //一级客户,查询下面的子客户
            parentId = sysOrgById.getId();
            parent = sysOrgById;
        } else {
            parentId = sysOrgById.getParentId();
            parent = baseMapper.selectById(parentId);
        }
        List<SysOrg> sysOrgs = baseMapper.selectByMap(ImmutableMap.of("parent_id", parentId, "delete_flag", 0));
        tempSysOrg.addAll(sysOrgs);
        //筛选
        tempSysOrg.forEach(temp -> {
            if (orgIds.contains(temp.getId())) {
                resultTemp.add(temp);
            }
        });
        List<String> temp = new ArrayList<>();
        tempSysOrg.forEach(e -> temp.add(e.getId()));
        if (orgIds.contains(parent.getId()) && !temp.contains(parent.getId())) {
            resultTemp.add(parent);
        }
        return OrgUtil.getOrgTree(resultTemp);
    }


    /**
     * 查询客户信息,登录用户有管理权限的客户
     *
     * @return
     */
    @Override
    public List<SysOrg> findOrgList(String businessType, String userId, Boolean isAdmin) {
        //获取登录用户的可管理客户
        return OrgUtil.getOrgTree(getUserMgrOrg(isAdmin, userId, businessType));
    }

    /**
     * 查询登录用户可管理可查看的客户以及子客户
     *
     * @param userId
     * @param isAdmin
     * @return
     */
    @Override
    public List<SysOrg> getOrgTreeByLoginUser(String businessType, String userId, boolean isAdmin) {
        SysUser sysUser = sysUserMapper.selectById(userId);
        Integer adminFlag = sysUser.getAdminFlag();
        List<SysOrg> allManageOrgByUser;
        //登录用户为空
        if (isAdmin || adminFlag == 1) {
            //查询全部
            QueryWrapper<SysOrg> query = new QueryWrapper<>();
            query.eq("delete_flag", "0");
            allManageOrgByUser = baseMapper.selectList(query);
            allManageOrgByUser.forEach(it -> {
                it.setManage(1);
                it.setRead(1);
            });
        } else {
            allManageOrgByUser = sysUserOrgMgrMapper.findAllOrgAndChildByUser(userId, null);
        }
        return OrgUtil.getOrgTree(allManageOrgByUser);
    }

    @Override
    public SysUserMgrDTO findOrgToOrderToPool(String userId, boolean isAdmin, String parameter, String businessType) {
        SysUserMgrDTO sysUserMgrDTO = new SysUserMgrDTO();
        SysUser sysUser = sysUserMapper.selectById(userId);
        //登录用户为空
        if (sysUser == null) {
            return sysUserMgrDTO;
        }
        //是否有管理设备池权限
        sysUserMgrDTO.setIsPool(sysUser.getStationFlag() == null ? 0 : sysUser.getStationFlag());
        //查看用户权限
        if (isAdmin) {
            sysUserMgrDTO.setIsPool(1);
        }
        if (sysUser.getAdminFlag() == 1) {
            isAdmin = true;
        }

        //所有订单
        List<SysUserModuleDTO> orderMgrs = sysOrderMapper.getOrderByOrgIds(null, parameter, businessType);

        //按客户授权的
        setOrderMgr(orderMgrs, sysUserMgrDTO, userId, isAdmin, parameter, businessType);
        //没有按客户授权，查询订单授权
        if (CollUtil.isEmpty(sysUserMgrDTO.getOrgMgrs())) {
            //订单授权的
            List<String> orderIds = sysUserOrderStationmgrMapper.findOrderMgrByUserId(userId);
            List<SysUserModuleDTO> mgrs = sysUserMgrDTO.getOrderMgrs();
            if (orderMgrs != null && orderMgrs.size() > 0) {
                orderMgrs.forEach(it -> {
                    if (orderIds.contains(it.getId())) {
                        mgrs.add(it);
                    }
                });
            }
            //查询可管理的订单
            sysUserMgrDTO.setOrderMgrs(mgrs);
        }
        return sysUserMgrDTO;
    }

    /**
     * 组装客户订单分组
     *
     * @param orderMgrs
     * @param sysUserMgrDTO
     * @param userId
     * @param isAdmin
     */
    public List<SysUserModuleDTO> setOrderMgr(List<SysUserModuleDTO> orderMgrs, SysUserMgrDTO sysUserMgrDTO, String userId, boolean isAdmin, String parameter, String
            businessType) {
        //查询可管理客户
        List<SysUserModuleDTO> orgMgrs = sysUserOrgMgrMapper.findOrgListByUserId(userId, isAdmin, null, businessType);
        if (orgMgrs != null) {
            List<SysUserModuleDTO> orgs = new ArrayList<>();
            List<SysUserModuleDTO> notOrgs = new ArrayList<>();
            String value = parameter == null ? "" : parameter;
            orgMgrs.forEach(it -> {
                if (it.getName().indexOf(value) != -1) {
                    orgs.add(it);
                } else {
                    notOrgs.add(it);
                }
            });
            sysUserMgrDTO.setOrgMgrs(orgs);
            Map<String, List<SysUserModuleDTO>> map = new HashMap<>();
            List<SysUserModuleDTO> orders = new ArrayList<>();
            List<SysUserModuleDTO> orderMgr = new ArrayList<>();
            orderMgrs.forEach(order -> {
                List<SysUserModuleDTO> moduleDTOs = map.get(order.getOrgId());
                if (moduleDTOs == null) {
                    moduleDTOs = new ArrayList<>();
                }
                if (!moduleDTOs.contains(order)) {
                    moduleDTOs.add(order);
                }
                map.put(order.getOrgId(), moduleDTOs);
            });
            orgs.forEach(org -> {
                List<SysUserModuleDTO> moduleDTOS = map.get(org.getId());
                org.setSysUserOrderMgrDTOs(moduleDTOS);
                if (moduleDTOS != null && moduleDTOS.size() > 0) {
                    moduleDTOS.forEach(it -> {
                        orders.add(it);
                    });
                }
            });

            notOrgs.forEach(it -> {
                List<SysUserModuleDTO> moduleDTOS = map.get(it.getId());
                if (moduleDTOS != null) {
                    moduleDTOS.forEach(order -> {
                        orders.add(order);
                        orderMgr.add(order);
                    });
                }
            });
            orderMgrs = CommonUtil.removeAll(orderMgrs, orders);
            if (isAdmin) {
                orderMgrs.forEach(it -> {
                    orderMgr.add(it);
                });
            }
            sysUserMgrDTO.setOrderMgrs(orderMgr);

        }
        return orderMgrs;
    }

    /**
     * 获取用户的可管理客户列表（admin获取全部列表）
     *
     * @param userId
     * @return
     */
    private List<SysOrg> getUserMgrOrg(boolean isAdmin, String userId, String businessType) {
        //判断用户是否是完全管理员
        SysUser sysUser = sysUserMapper.selectById(userId);

//        boolean isAdmin  =  sysUserService.isAdmin(userId);
        Integer adminFlag = sysUser.getAdminFlag();
        List<SysOrg> allManageOrgByUser = new ArrayList<>();
        //登录用户为空
        if (isAdmin || adminFlag == 1) {
            //查询全部
            QueryWrapper<SysOrg> query = new QueryWrapper<>();
            query.eq("delete_flag", "0");
            if (!StringUtils.isEmpty(businessType)) {
                query.eq("business_type", businessType);
            }
            allManageOrgByUser = baseMapper.selectList(query);
            allManageOrgByUser.forEach(e -> {
                e.setRead(1);
                e.setManage(1);
            });
        } else {
            List<String> manageOneList = sysUserOrgMgrMapper.findAllOrgAndChildByUser(userId, null)
                    .stream().filter(it -> WamingConstant.ONE.equals(it.getManage()))
                    .map(SysOrg::getId)
                    .collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(manageOneList)) {
                QueryWrapper<SysOrg> query = new QueryWrapper<>();
                query.in("id", manageOneList);
                query.eq("delete_flag", 0);
                allManageOrgByUser = baseMapper.selectList(query);
            }
        }
        return allManageOrgByUser;
    }

    /**
     * 功能描述: 获取业务类型
     *
     * @param:
     * @return:
     * @auther: Destiny
     * @date: 2020/12/29 上午10:47
     */
    @Override
    public List<SysBusinessTypeDTO> getBusinessType(String userId) {
        LoginUserDTO userDTO = sysUserMapper.findLoginUserInfo(userId);
        boolean orgAdmin = userDTO.getOrgAdminFlag() != null && userDTO.getOrgAdminFlag() == 1;
        boolean adminFlag = false;
        if ((userDTO.getAdminFlag() != null && userDTO.getAdminFlag() == 1)
                || userDTO.getUsername().equals(SecurityConstants.ADMIN_USER_NAME)) {
            adminFlag = true;
        }
        return sysOrderMapper.getBusinessTypeByUserId(userId, adminFlag, orgAdmin);
    }

    /**
     * 管理权限APPP
     */
    @Override
    public List<SysBusinessTypeDTO> getManageBusinessApp(String userId) {
        LoginUserDTO userDTO = sysUserMapper.findLoginUserInfo(userId);
        boolean orgAdmin = userDTO.getOrgAdminFlag() != null && userDTO.getOrgAdminFlag() == 1;
        boolean adminFlag = false;
        if ((userDTO.getAdminFlag() != null && userDTO.getAdminFlag() == 1)
                || userDTO.getUsername().equals(SecurityConstants.ADMIN_USER_NAME)) {
            adminFlag = true;
        }
        //查询有权限的应用
        List<SysBusinessTypeDTO> dtoList = sysOrderMapper.getBusinessTypeByUserId(userId, adminFlag, orgAdmin);

        if (adminFlag) {
            return dtoList;
        } else {
            //用户可管理应用列表
            Set<Integer> manageAppId = sysUserRoleMapper.findManageAppId(userId);
            return dtoList.stream().filter(it -> manageAppId.contains(Integer.parseInt(it.getBizCode()))).toList();
        }
    }

    /**
     * 用户身份
     *
     * @return
     */
    public List<Map<String, Object>> getRoleByBusinessType(String businessType, String userId) {
        LoginUserDTO userDTO = sysUserMapper.findLoginUserInfo(userId);
        boolean orgAdmin = userDTO.getOrgAdminFlag() != null && userDTO.getOrgAdminFlag() == 1;
        boolean adminFlag = false;
        if ((userDTO.getAdminFlag() != null && userDTO.getAdminFlag() == 1)
                || userDTO.getUsername().equals(SecurityConstants.ADMIN_USER_NAME)) {
            adminFlag = true;
        }
        //所有业务类型
        List<SysBusinessTypeDTO> dtoList = sysOrderMapper.getBusinessTypeByUserId(userId, adminFlag, orgAdmin);
        Map<String, SysBusinessTypeDTO> businessTypeMap = dtoList.stream().collect(Collectors.toMap(SysBusinessTypeDTO::getValue, o -> o));

        List<SysBusinessTypeDTO> realTypes = new ArrayList<>();
        //如果businessType为空查询所有
        if (!StringUtils.isEmpty(businessType)) {
            List<String> typeList = Arrays.asList(businessType.split(","));
            for (String type : typeList) {
                SysBusinessTypeDTO businessTypeDTO = businessTypeMap.get(type);
                if (businessTypeDTO != null) {
                    realTypes.add(businessTypeDTO);
                }
            }
        } else {
            realTypes = dtoList;
        }

        Set<String> typeSet = realTypes.stream().map(SysBusinessTypeDTO::getValue).collect(Collectors.toSet());

        List<Map<String, Object>> dataList = new ArrayList<>();
        for (SysBusinessTypeDTO dto : realTypes) {
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("value", dto.getValue());
            dataMap.put("label", dto.getName());

            //所有业务类型
            List<SysBusinessTypeDTO> roleList = sysOrderMapper.getRoleByBusinessType(dto.getValue());
            List<Map<String, Object>> roleDataList = new ArrayList<>();
            for (SysBusinessTypeDTO businessTypeDTO : roleList) {
                Map<String, Object> roleMap = new HashMap<>();
                roleMap.put("value", businessTypeDTO.getValue());
                roleMap.put("label", businessTypeDTO.getName());
                roleDataList.add(roleMap);
            }
            dataMap.put("children", roleDataList);

            dataList.add(dataMap);
        }
        //设计器普通角色
        if (!typeSet.contains("13")) {
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("value", "13");
            dataMap.put("label", "轻云设计器");
            Map<String, Object> roleMap = new HashMap<>();
            roleMap.put("value", "6");
            roleMap.put("label", sysRoleMapper.selectById(6).getName());
            List<Map<String, Object>> roleDataList = new ArrayList<>();
            roleDataList.add(roleMap);
            dataMap.put("children", roleDataList);
            dataList.add(dataMap);
        }

        if (!typeSet.contains("11")) {
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("value", "11");
            dataMap.put("label", "设计器资源管理");
            Map<String, Object> roleMap = new HashMap<>();
            roleMap.put("value", "375");
            roleMap.put("label", sysRoleMapper.selectById(375).getName());
            List<Map<String, Object>> roleDataList = new ArrayList<>();
            roleDataList.add(roleMap);
            dataMap.put("children", roleDataList);
            dataList.add(dataMap);
        }

        return dataList;
    }

    /**
     * 功能描述: 获取授权用户的业务种类和角色
     *
     * @param: userId
     * @return:
     * @auther: Destiny
     * @date: 2021/1/4 下午4:33
     */
    public List<Map<String, Object>> getRoleBusinessTypeByAuthorUser(String userId) {
        //所有业务类型
        List<SysBusinessTypeDTO> data = sysOrderMapper.getBusinessTypeByUserId(null, true, true);
        Map<String, SysBusinessTypeDTO> businessTypeMap = data.stream().collect(Collectors.toMap(SysBusinessTypeDTO::getValue, o -> o));

        List<UserRoleBo> roleBoList = sysUserRoleMapper.findRoleInfoByUserId(userId);

        for (UserRoleBo roleBo : roleBoList) {
            SysBusinessTypeDTO typeDTO = businessTypeMap.get(roleBo.getBusinessType());
            roleBo.setBusinessName(typeDTO.getName());
        }

        Map<String, List<UserRoleBo>> groups = roleBoList.stream().collect(Collectors.groupingBy(s -> s.getBusinessType()));

        List<Map<String, Object>> dataList = new ArrayList<>();
        for (Map.Entry<String, List<UserRoleBo>> entry : groups.entrySet()) {
            String key = entry.getKey();

            SysBusinessTypeDTO typeDTO = businessTypeMap.get(key);
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("value", key);
            dataMap.put("label", typeDTO.getName());
            List<UserRoleBo> value = entry.getValue();

            List<String> roleIds = new ArrayList<>();
            value.forEach(it -> {
                roleIds.add(it.getRoleId());
            });
            dataMap.put("originalFunction", sysUserRoleMapper.findRoleFunction(roleIds));

            List<Map<String, Object>> roleDataList = new ArrayList<>();
            for (UserRoleBo userRoleBo : value) {
                Map<String, Object> roleMap = new HashMap<>();
                roleMap.put("value", userRoleBo.getRoleId());
                roleMap.put("label", userRoleBo.getRoleName());
                roleDataList.add(roleMap);
                dataMap.put("children", roleDataList);
            }
            dataList.add(dataMap);
        }

        return dataList;
    }

    /**
     * 根据机构ID和业务种类查询机构信息
     */
    @Override
    public List<SysOrgInfo> findOrgInfo(OrgInfoParam orgInfoParam) {
        return sysOrgMapper.findOrgInfo(orgInfoParam);
    }

    /**
     * 根据父客户ID，查询客户下的分支机构
     *
     * @param parentId 父客户ID
     * @return 分支机构信息
     */
    @Override
    public List<SysOrgInfo> findChild(String parentId) {
        return sysOrgMapper.findChildInfo(parentId);
    }

    @Override
    public List<SysOrgUserInfo> getOrgUserTree(String userId) {
        List<SysOrg> allManageOrgByUser;
        //登录用户为空
        if (sysUserService.isAdmin(userId)) {
            //查询全部
            QueryWrapper<SysOrg> query = new QueryWrapper<>();
            query.eq("delete_flag", "0");
            allManageOrgByUser = baseMapper.selectList(query);
            allManageOrgByUser.forEach(it -> {
                it.setManage(1);
                it.setRead(1);
            });
        } else {
            allManageOrgByUser = sysUserOrgMgrMapper.findAllOrgAndChildByUser(userId, null);
        }
        List<SysOrgUserInfo> sysOrgUserInfo = new ArrayList<>();
        List<String> orgIds = allManageOrgByUser.stream().map(SysOrg::getId).collect(Collectors.toList());
        List<SysUserVo> sysUsers = sysUserMapper.findUserByOrgId(orgIds);
        Map<String, List<SysUserVo>> collect = sysUsers.stream().collect(Collectors.groupingBy(SysUserVo::getOrgId));
        for (SysOrg org : allManageOrgByUser) {
            SysOrgUserInfo info = new SysOrgUserInfo();
            BeanUtil.copyProperties(org, info);
            info.setUserListVo(collect.get(org.getId()));
            sysOrgUserInfo.add(info);
        }
        return sysOrgUserInfo;
    }

    @Override
    public Set<String> findReadableUserTaskOrgIds(String userId) {
        //是否超管
        if (WamingConstant.ADMIN_USER_ID.equals(userId)) {
            //筛选全部监测点
            return userTaskOrgMapper.getAllTaskOrg(true, userId);
        }
        SysUser sysUser = sysUserMapper.selectById(userId);
        //登录用户为空
        if (sysUser == null) {
            return Collections.emptySet();
        }
        boolean isAdmin = false;
        //完全管理权限
        if (sysUser.getAdminFlag() == 1) {
            isAdmin = true;
        }
        return userTaskOrgMapper.getAllTaskOrg(isAdmin, userId).stream().filter(StrUtil::isNotBlank)
                .collect(Collectors.toSet());
    }

    @Override
    public String findUserTaskOrg(String userId) {
        String orgId = userTaskOrgMapper.findUserTaskOrgId(userId);
        if (StrUtil.isBlank(orgId)) {
            return "";
        }
        return orgId;
    }

    /**
     * 按名称统计企业数量
     */
    @Override
    public int countOrgByName(String name) {
        Long count = sysOrgMapper.selectCount(Wrappers.<SysOrg>lambdaQuery().eq(SysOrg::getName, name)
                .eq(SysOrg::getDeleteFlag, 0));
        return  count.intValue();
    }

    /**
     * 云平台注册组织
     */
    @Override
    public String registerOrg(String name) {
        //创建组织
        SysOrg newOrg = new SysOrg();
        String id = UlidCreator.getMonotonicUlid().toString().toLowerCase();
        newOrg.setName(name).setShortName(name).setFullName(name).setType(2).setBusinessType("3,5,11").setCategory(1)
                .setDeleteFlag(0).setCreateDt(new Date()).setCreateBy("cloud").setId(id);
        sysOrgMapper.insert(newOrg);

        //组织管理员默认业务种类-通用管理平台、融合平台、资源管理
        List<SysOrgLogoDTO> list = new ArrayList<>();
        SysOrgLogoDTO dtoAdmin = new SysOrgLogoDTO();
        dtoAdmin.setOrgId(newOrg.getId());
        dtoAdmin.setBusinessType("3");
        list.add(dtoAdmin);

        dtoAdmin = new SysOrgLogoDTO();
        dtoAdmin.setOrgId(newOrg.getId());
        dtoAdmin.setBusinessType("13");
        list.add(dtoAdmin);

        dtoAdmin = new SysOrgLogoDTO();
        dtoAdmin.setOrgId(newOrg.getId());
        dtoAdmin.setBusinessType("11");
        list.add(dtoAdmin);
        sysOrgMapper.insertOrgLogo(list);
        return id;
    }
}

